package main

import (
	"github.com/example/video_backend/internal/model"
	"github.com/example/video_backend/pkg/logger"
	"github.com/example/video_backend/pkg/minio"
	"github.com/spf13/viper"
	"log"
)

func InitGlobal() {
	// 初始化配置
	initConfig()

	// 初始化日志
	if err := logger.InitLogger(); err != nil {
		log.Fatalf("Failed to initialize logger: %v", err)
	}

	// 初始化数据库
	initDB()

	// 初始化Redis
	initRedis()

	//初始化MinIO
	if err := minio.InitMinIO(); err != nil {
		logger.Fatal("Failed to initialize MinIO: " + err.Error())
	}
}

// 初始化配置
func initConfig() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("configs/")
	viper.AddConfigPath("./")

	// 设置默认值
	viper.SetDefault("server.port", "8081")
	viper.SetDefault("database.driver", "mysql")
	viper.SetDefault("database.host", "localhost")
	viper.SetDefault("database.port", "3306")
	viper.SetDefault("database.username", "root")
	viper.SetDefault("database.password", "password")
	viper.SetDefault("database.dbname", "video_platform")
	viper.SetDefault("database.charset", "utf8mb4")
	viper.SetDefault("redis.host", "localhost")
	viper.SetDefault("redis.port", "6379")
	viper.SetDefault("minio.endpoint", "192.168.31.147:9000")
	viper.SetDefault("minio.access_key", "minio")
	viper.SetDefault("minio.secret_key", "minio123")
	viper.SetDefault("minio.use_ssl", false)
	viper.SetDefault("minio.bucket_name", "videos")
	viper.SetDefault("minio.location", "us-east-1")
	viper.SetDefault("jwt.secret", "your-secret-key")
	viper.SetDefault("jwt.expire_time", 72) // 单位：小时
	viper.SetDefault("logger.level", "info")
	viper.SetDefault("logger.path", "logs")
	viper.SetDefault("logger.filename", "app.log")
	viper.SetDefault("logger.max_size", 500)
	viper.SetDefault("logger.max_age", 7)
	viper.SetDefault("logger.max_backups", 3)
	viper.SetDefault("logger.compress", false)
	viper.SetDefault("logger.console_output", true)
	viper.SetDefault("server.port", "8081")
	// 读取环境变量
	viper.AutomaticEnv()

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		log.Printf("Warning: Config file not found, using defaults: %v", err)
	}
}

// 初始化数据库
func initDB() {
	dbConfig := model.DBConfig{
		Driver:   viper.GetString("database.driver"),
		Host:     viper.GetString("database.host"),
		Port:     viper.GetString("database.port"),
		Username: viper.GetString("database.username"),
		Password: viper.GetString("database.password"),
		DBName:   viper.GetString("database.dbname"),
		Charset:  viper.GetString("database.charset"),
	}

	// 初始化数据库连接
	if err := model.InitDB(dbConfig); err != nil {
		logger.Fatal("Failed to initialize database: " + err.Error())
	}

	// 自动迁移表结构
	model.AutoMigrate()
}

// 初始化Redis
func initRedis() {
	redisConfig := model.RedisConfig{
		Host: viper.GetString("redis.host"),
		Port: viper.GetString("redis.port"),
	}

	if err := model.InitRedis(redisConfig); err != nil {
		logger.Fatal("Failed to initialize Redis: " + err.Error())
	}
}
